package com.itserver.utils.interceptor;


import com.itserver.utils.Config;
import com.itserver.utils.RedisCache;
import io.jsonwebtoken.Claims;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import com.itserver.utils.CurrentHolder;
import com.itserver.utils.JwtUtils;
import com.itserver.utils.exception.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private Config config;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AuthenticationException {
        String url = request.getRequestURI();
        log.info("拦截器：preHandle 执行了:{} ", url);
        //获取请求头中的token
        String token = request.getHeader(config.getAuthentication());
        //判断token是否存在
        if (token == null || token.isEmpty()) {
            //不存在，返回错误信息
            log.info("token不存在");
            throw new AuthenticationException("token不存在，请先登录");
        }
        // 判断token是否在黑名单中
        if (redisCache.isTokenExist(token)) {
            throw new AuthenticationException("token已失效，请重新登录");
        }
        // 判断token是否在登录用户列表中
        if (!redisCache.isLoginUserExist(token)) {
            //不存在，返回错误信息
            log.info("token不存在");
            throw new AuthenticationException("token不存在，请先登录");
        }
        //如果存在 验证token
        Claims claims = JwtUtils.parseJWT(token);
        if (claims == null) {
            //验证失败
            log.info("token验证失败 返回401");
            throw new AuthenticationException("token验证失败，请重新登录");
        }

        CurrentHolder.setCurrent(claims.get("username"));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURI();
        // 删除线程局部变量
        CurrentHolder.remove();
        log.info("拦截器：afterCompletion 执行了 删除线程局部变量{}",url);
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }


}
